# -*- coding: utf-8 -*-
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
import config

end_flag = False
weight = 0


def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    return " ".join(l)


async def main():
    print("starting scan...")

    # 基于设备地址查找设备
    device = await BleakScanner.find_device_by_address(config.device_address)
    if device is None:
        print("could not find device with address '%s'", config.device_address)
        return

    print("connecting to device...")

    async with BleakClient(device) as client:
        print("connected")

        def notification_handler(sender, data):
            global end_flag
            global weight
            print(f"{sender}: {print_hex(data)}")
            if len(data) == 12 and data[5] == 2:
                weight = data[3] * 16 * 16 + data[4]
                end_flag = True

        await client.start_notify(config.notify_uuid, notification_handler)
        await client.write_gatt_char(config.write_uuid, bytes(config.open_data1))
        await client.write_gatt_char(config.write_uuid, bytes(config.open_data2))
        await client.write_gatt_char(config.write_uuid, bytes(config.open_data3))

        while not end_flag:
            await asyncio.sleep(1.0)  # 监听1秒

        await client.write_gatt_char(config.write_uuid, bytes(config.close_data))
        await client.stop_notify(config.notify_uuid)
        print(f"接收体重: {weight/100}")


if __name__ == "__main__":
    asyncio.run(main())